package phasebook.impl;

import java.util.Properties;

import javax.ejb.Stateless;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Stateless
public class MailSender {
	
	public void postMail(final String message, final String subject, final String targetAddress) throws MessagingException{	

		  new Thread(){
			   public void run(){
					// Setup mail server 
			        Properties props = System.getProperties(); 
			        props.put("mail.smtp.host", "smtp.gmail.com");
			        props.put("mail.smtp.auth", "true");
			        props.put("mail.debug", "true");
			        props.put("mail.smtp.port", "465");
			        props.put("mail.smtp.socketFactory.port", "465");
			        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			        props.put("mail.smtp.socketFactory.fallback", "false");

			        Authenticator auth = new SMTPAuthenticator();
			        
			        Session session = Session.getDefaultInstance(props, auth);
			        
			        session.setDebug(true);
			        
			        // create a message
			        Message msg = new MimeMessage(session);

			        try {
				        // set the from and to address
				        InternetAddress addressFrom = new InternetAddress("mse.si.st@gmail.com");
				        msg.setFrom(addressFrom);
		
				        InternetAddress addressTo = new InternetAddress(targetAddress);
				        msg.setRecipient(Message.RecipientType.TO, addressTo);
				        
				        // Setting the Subject and Content Type
				        msg.setSubject(subject);
							msg.setContent(message, "text/plain");
				        Transport.send(msg);
					} catch (MessagingException e) {
						System.out.println("Error sending email.");
						e.printStackTrace();
					}
			   }
			  }.start();
	}

	private class SMTPAuthenticator extends javax.mail.Authenticator
	{
	    public PasswordAuthentication getPasswordAuthentication()
	    {
	        String username = "mse.si.st";
	        String password = "socialiters";
	        return new PasswordAuthentication(username, password);
	    }
	}
}
